package controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;


import entity.*;

import service.*;

import util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
@WebServlet("/schoolctl")
public class SchoolController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        String req_jsonStr= JSONUtil.getJSON(request);
        JSONObject req_json = JSON.parseObject(req_jsonStr);
        if(req_json==null){
            message.put("message","未收到信息");
            response.getWriter().println(message.toJSONString());
            return;
        }

        try {
            Pagination pagination= ControllerHelper.getPagination(req_json);

            Collection<School> schools = SchoolService.getInstance().findAll(pagination);

            String school_json = JSON.toJSONString(schools, JSONWriter.Feature.ReferenceDetection);
            message.put("totalNum",pagination.getTotalNum());
            message.put("data",school_json);
            response.getWriter().println(message);
        } catch (SQLException e){
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }finally {
            response.getWriter().close();
        }
    }
}
